package cn.wanho.config;

import cn.wanho.dao.CmsUserMapper;
import cn.wanho.util.PassEnDeUtil;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.security.crypto.password.PasswordEncoder;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;


/**
 * 记得要在配置类中注入为@Bean
 */
public class MyCustomerPasswordEncoder implements PasswordEncoder {

    @Resource
    private HttpServletRequest request;
    @Resource
    private CmsUserMapper cmsUserMapper;
    private final Log logger = LogFactory.getLog(getClass());

    @Override
    public String encode(CharSequence rawPassword) {
        if (rawPassword == null) {
            throw new IllegalArgumentException("rawPassword cannot be null");
        }
        String salt = getSalt();


        String pass = rawPassword.toString();
        System.out.println("pass:"+pass);
        String digestHex = PassEnDeUtil.encoder(pass,salt);
        System.out.println(digestHex);
        return digestHex;
    }

    private String getSalt() {
        String username = request.getParameter("username");
        String salt = cmsUserMapper.selectByUsername(username).getSalt();
        //请在此处定义数据库操作的salt的盐的拿去



        if (salt != null) {
            return salt;
        }else{
            return null;
        }

    }

    /**
     * 输入密码对比
     * @param rawPassword 原始输入密码
     * @param encodedPassword 加密密码
     * @return
     */
    @Override
    public boolean matches(CharSequence rawPassword, String encodedPassword) {
        System.out.println("rawPass::"+rawPassword);
        System.out.println("----matches---");
        if (rawPassword == null) {
            throw new IllegalArgumentException("rawPassword cannot be null");
        }
        if (encodedPassword == null || encodedPassword.length() == 0) {
            this.logger.warn("Empty encoded password");
            return false;
        }

      ;
        //   String encodePass = encodedPassword.toString();
        //  System.out.println("encodePass:"+encodePass);
        //请从数据库总查看对应的sql中存入的密码字段赋值给rawPass
        String salt = getSalt();
        String digestHex01 = PassEnDeUtil.encoder(rawPassword.toString(),salt);
//        System.out.println("digestHex01:"+digestHex01);
        return digestHex01.equals(encodedPassword);
    }


}
